import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';
import morgan from 'morgan';
import ejsMate from 'ejs-mate';

import { db, runMigrations } from './utils/db.js';
import authRouter from './routes/auth.js';
import tenderRouter from './routes/tenders.js';
import bidRouter from './routes/bids.js';
import messageRouter from './routes/messages.js';
import adminRouter from './routes/admin.js';
import { requireAuth } from './utils/auth.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();

app.use(helmet());
app.use(morgan('dev'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(
  session({
    secret: 'pharma-tender-secret',
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true }
  })
);

app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/public', express.static(path.join(__dirname, '..', 'public')));

app.use((req, res, next) => {
  res.locals.currentUser = req.session.user || null;
  res.locals.currentPath = req.path;
  next();
});

app.get('/', (req, res) => {
  if (!req.session.user) {
    return res.redirect('/auth/login');
  }
  return res.redirect('/dashboard');
});

app.get('/dashboard', requireAuth, (req, res) => {
  res.render('dashboard', { role: req.session.user.role, title: '控制台' });
});

app.use('/auth', authRouter);
app.use('/tenders', tenderRouter);
app.use('/bids', bidRouter);
app.use('/messages', messageRouter);
app.use('/admin', adminRouter);

app.use((err, req, res, next) => {
  console.error(err);
  if (res.headersSent) {
    return next(err);
  }
  if (req.accepts('html')) {
    res.status(500).render('error', { message: err.message || '服务器内部错误' });
  } else {
    res.status(500).json({ error: err.message || '服务器内部错误' });
  }
});

const PORT = process.env.PORT || 3000;
runMigrations();
app.listen(PORT, () => {
  db.pragma('journal_mode = WAL');
  console.log(`Server listening on http://localhost:${PORT}`);
});


